﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using TarreOA.TarreOADAL;
using System.IO;

public partial class Flow_Info_afdownload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString.Get("afid") != null)
        {
            int afid = int.Parse(Request.QueryString.Get("afid"));
            string filepath = "";
            string orifilename = "";
            bool exists = false;
            SqlConnection sqlconn = null;
            SqlCommand sqlcmd = null;
            SqlDataReader sqldr = null;
            try
            {
                sqlconn = SQLManager.GetConn();
                string sql = "select filepath,filename from flow_newworkaffixfile where id=" + afid;
                sqlconn.Open();
                sqlcmd = new SqlCommand(sql, sqlconn);
                sqldr = sqlcmd.ExecuteReader();
                if (sqldr.HasRows)
                {
                    sqldr.Read();
                    filepath = sqldr["filepath"].ToString();
                    orifilename = sqldr["filename"].ToString();
                }
                if (!"".Equals(filepath) && !"".Equals(orifilename))
                {
                    DirectoryInfo dirinfo = new DirectoryInfo(Server.MapPath("affix_download"));
                    if (!dirinfo.Exists)
                        dirinfo.Create();
                    FileInfo[] files = dirinfo.GetFiles();
                    if(files != null)
                        foreach (FileInfo fi in files)
                        {
                            fi.Delete();
                        }
                    FileInfo orifile = new FileInfo(filepath);
                    if (orifile.Exists)
                    {
                        orifile.CopyTo(Server.MapPath("affix_download\\" + orifilename));
                        exists = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                if(sqlconn != null)
                    if (sqlconn.State == ConnectionState.Open)
                    {
                        sqlconn.Close();
                        sqlconn.Dispose();
                    }
                if (sqldr != null)
                {
                    sqldr.Close();
                    sqldr.Dispose();
                }
            }
            if (exists)
            {
                Response.Redirect("affix_download/" + orifilename);
            }
        }
    }
}
